<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" destroyOnClose :title="title" width="600px" :showFooter="false">
    <a-form :model="formState" ref="userRole">
      <a-form-item name="roleIds">
        <vxe-table border resizable ref="treeTable" :row-config="{ keyField: 'menuId' }" :tree-config="{ children: 'children', expandAll: true }" :checkbox-config="{ checkStrictly: false, labelField: 'menuName', checkRowKeys: checkRowKeys }" :data.sync="selectMenus">
          <vxe-column type="checkbox" title="菜单" tree-node width="220"></vxe-column>
          <vxe-column field="operation" title="操作" align="left">
            <template #default="{ row }">
              <a-checkbox-group :value="formState.grantActions" :key="row.menuId">
                <a-checkbox :disabled="item.disabled" v-for="(item, index) in row.actionList" :key="index" :value="item.authorityId" @change="setActions">
                  <span :title="item.actionDesc">{{ item.actionName }}</span>
                </a-checkbox>
              </a-checkbox-group>
            </template>
          </vxe-column>
        </vxe-table>
      </a-form-item>
    </a-form>
  </BasicDrawer>
</template>
<script lang="ts" name="lookRoleAuth" setup>
import { reactive, ref } from 'vue';
import { BasicDrawer, useDrawerInner } from '@/components/drawer';
import { getAuthorityMenu, getAuthorityRole } from '../../role/data/role.api';
import XEUtils from 'xe-utils';

const treeTable: any = ref();
const userRole = ref();
const checkRowKeys: any = ref([]);
const selectMenus: any = ref([]);
let actionIds: any = new Set();
const formState = reactive({
  roleId: '',
  grantActions: <any>[],
  grantMenus: <any>[],
  isExpired: false,
});
const title = ref('');
//表单赋值
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  const item = data.item;
  title.value = item.nickName + '-' + item.roleName + '-角色权限';
  setData(item);
});

/**
 * 设置数据
 * @param item
 */
async function setData(item) {
  formState.roleId = item.roleId;
  await handleLoadRoleGranted(item.roleId);
}

/*获取已选择节点*/
async function getCheckedAuthorities() {
  const menuIds = new Set();
  treeTable.value.getCheckboxRecords().map((item) => {
    menuIds.add(item.authorityId);
  });
  treeTable.value.getCheckboxIndeterminateRecords().map((item) => {
    menuIds.add(item.authorityId);
  });
  return Array.from(menuIds).concat(formState.grantActions);
}

function setActions(e) {
  if (e.target.checked) {
    actionIds.add(e.target.value);
  } else {
    actionIds.delete(e.target.value);
  }
  formState.grantActions = Array.from(actionIds);
}

/*加载权限*/
async function handleLoadRoleGranted(roleId) {
  if (!roleId) {
    return;
  }
  const p1 = getAuthorityMenu();
  const p2 = getAuthorityRole(roleId);
  Promise.all([p1, p2]).then((values) => {
    let res1: any = values[0];
    let res2: any = values[1];
    if (res1) {
      if (res2 && res2.length > 0) {
        let menus: any = [];
        let actions: any = [];
        res2.map((item) => {
          // 菜单权限
          if (item.authority.indexOf('MENU_') != -1 && !menus.includes(item.authorityId)) {
            menus.push(item.authorityId);
          }
          // 操作权限
          if (item.authority.indexOf('ACTION_') != -1 && !actions.includes(item.authorityId)) {
            actions.push(item.authorityId);
          }
        });
        formState.grantMenus = menus;
        formState.grantActions = actions;
        actionIds = new Set(actions);
      }
      res1.map((item) => {
        // 菜单选中
        if (formState.grantMenus.includes(item.authorityId)) {
          if (item.parentId != '0') {
            //排除一级节点避免全部选中
            checkRowKeys.value.push(item.menuId);
          }
        }
      });
      let opt = {
        key: 'menuId',
        parentKey: 'parentId',
        children: 'children',
      };
      selectMenus.value = XEUtils.toArrayTree(res1, opt);
    }
  });
}
</script>
<style scoped lang="less"></style>
